package com.thz.friend.manager;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.thz.common.core.constants.CacheConstants;
import com.thz.common.core.constants.RedisConstants;
import com.thz.friend.mapper.user.UserMapper;
import com.thz.friend.pojo.user.User;
import com.thz.friend.pojo.user.vo.UserVO;
import com.thz.redis.utlis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author thz
 * @Date 2025/3/27
 */
@Slf4j
@Component
public class UserCacheManager {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserMapper userMapper;

    public UserVO getUserById(Long userId) {
        String userKey = getUserCacheKey(userId);
        UserVO userVO = redisUtil.getCacheObject(userKey, UserVO.class);
        // userVO 存在 延长redis的时间，返回
        if (userVO != null) {
            redisUtil.expire(userKey, CacheConstants.USER_EXP, TimeUnit.MINUTES);
            return userVO;
        }
        // userVO 不存在，从mysql中去获取
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .select(User::getUserId,User::getNickName,User::getHeadImage,User::getSex,
                        User::getPhone,User::getEmail,User::getWechat,User::getSchoolName,
                        User::getMajorName,User::getIntroduce,User::getStatus)
                .eq(User::getUserId, userId));
        // mysql中不存在 -- 用户不存在直接返回Null
        if (user == null) {
            return null;
        }
        // 更新缓存
        userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        refreshUser(userVO);
        return userVO;
    }

    public void refreshUser(UserVO userVO) {
        // 刷新用户缓存
        String userKey = getUserCacheKey(userVO.getUserId());
        redisUtil.setCacheObject(userKey, userVO);
        //设置用户缓存有效期为10分钟
        redisUtil.expire(userKey, CacheConstants.USER_EXP, TimeUnit.MINUTES);
    }

    private String getUserCacheKey(Long userId) {
        return redisUtil.buildKey(RedisConstants.C_USER_DETAIL_KEY, userId.toString());
    }



}
